package com.pro.app.controller;


import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pro.app.annotation.LoginUser;
import com.pro.core.util.ResponseUtil;
import com.pro.core.validator.NotNullValidator;
import com.pro.db.domain.BbsComment;
import com.pro.db.domain.BbsTopic;
import com.pro.db.domain.ProUser;
import com.pro.db.service.itf.IBbsCommentService;
import com.pro.db.service.itf.IBbsTopicService;
import com.pro.db.service.itf.IProUserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static com.baidu.unbiz.fluentvalidator.ResultCollectors.toComplex;


/**
 * <p>
 * 帖子表 前端控制器
 * </p>
 *
 * @author 王雷
 * @since 2020-01-07
 */
@RestController
@RequestMapping("/app/bbsTopic")
public class AppBbsTopicController {
    private final Log logger = LogFactory.getLog(AppBbsTopicController.class);

    @Autowired
    private IBbsTopicService bbsTopicService;

    @Autowired
    private IProUserService userService;

    @Autowired
    private IBbsCommentService bbsCommentService;

    /**
     * @apiDefine bbsTopic 帖子接口
     *
     */

    /**
     * @api {GET} /app/bbsTopic/list 5.1 获取板块下的帖子列表
     * @apiName bbsTopic list
     * @apiGroup bbsTopic
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} forumId 板块id
     * @apiParam {int} type 1：全部(默认)  2：最新  3： 热门  4：精华
     * @apiParam {int} [page] 页码
     * @apiParam {int} [size] 每页数量
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/list")
    public Object list(@NotNull Integer forumId,Integer type,
                       @RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer size) {
        Page<BbsTopic> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        IPage<BbsTopic> pList = null;
        if(null == type || type == 1 ){
            pList = bbsTopicService.page(pageVo,
                    new QueryWrapper<BbsTopic>()
                            /* .select("id","site_id","forum_id","name","description","cover_url",
                                     "cover_type","label","keywords","read_num","like_num",
                                     "favor_num","comment_num","hot_tag","create_user_id","create_username",
                                     "create_nickname","create_avatar","add_time")*/
                            .eq("deleted",0)
                            .eq("forum_id",forumId)
                            .orderByDesc("add_time"));
        }else if(type == 2){
            pList = bbsTopicService.page(pageVo,
                    new QueryWrapper<BbsTopic>()
                            /* .select("id","site_id","forum_id","name","description","cover_url",
                                     "cover_type","label","keywords","read_num","like_num",
                                     "favor_num","comment_num","hot_tag","create_user_id","create_username",
                                     "create_nickname","create_avatar","add_time")*/
                            .eq("deleted",0)
                            .eq("forum_id",forumId)
                            .orderByDesc("update_time"));
        }else if(type == 3){
            pList = bbsTopicService.page(pageVo,
                    new QueryWrapper<BbsTopic>()
                            /* .select("id","site_id","forum_id","name","description","cover_url",
                                     "cover_type","label","keywords","read_num","like_num",
                                     "favor_num","comment_num","hot_tag","create_user_id","create_username",
                                     "create_nickname","create_avatar","add_time")*/
                            .eq("deleted",0)
                            .eq("forum_id",forumId)
                            .orderByDesc("comment_num"));
        }else if(type == 4){
            pList = bbsTopicService.page(pageVo,
                    new QueryWrapper<BbsTopic>()
                            /* .select("id","site_id","forum_id","name","description","cover_url",
                                     "cover_type","label","keywords","read_num","like_num",
                                     "favor_num","comment_num","hot_tag","create_user_id","create_username",
                                     "create_nickname","create_avatar","add_time")*/
                            .eq("deleted",0)
                            .eq("forum_id",forumId)
                            .eq("hot_tag",1)
                            .orderByDesc("add_time"));
        }

        for(BbsTopic topic:pList.getRecords()){
            BbsComment comment = bbsCommentService.getOne(new QueryWrapper<BbsComment>()
                    .eq("topic_id",topic.getId())
                    .orderByDesc("add_time"));
            topic.setLastComment(comment);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }


    /**
     * @api {GET} /app/bbsTopic/read 5.2 帖子详情
     * @apiName bbsTopic read
     * @apiGroup bbsTopic
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 帖子id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        BbsTopic entity = bbsTopicService.getById(id);
        try{
            BbsTopic update = new BbsTopic();
            update.setId(entity.getId());
            update.setReadNum(entity.getReadNum()+1);
            bbsTopicService.updateById(update);
        }catch (Exception e){
            e.printStackTrace();
        }
        ProUser user = userService.getById(entity.getCreateUserId());
        user.setPassword(null);
        entity.setUser(user);

        BbsTopic prev = bbsTopicService.getOne(new QueryWrapper<BbsTopic>()
                .select("id","name","description","add_time")
                .eq("forum_id",entity.getForumId())
                .eq("deleted",0)
                .gt("id",entity.getId())
                .orderByAsc("id"));
        if(null != prev){
            entity.setPrevTopic(prev);
        }

        BbsTopic next = bbsTopicService.getOne(new QueryWrapper<BbsTopic>()
                .select("id","name","description","add_time")
                .eq("forum_id",entity.getForumId())
                .eq("deleted",0)
                .lt("id",entity.getId())
                .orderByDesc("id"));
        if(null != next){
            entity.setNextTopic(next);
        }

        return ResponseUtil.ok(entity);
    }

    /**
     * @api {POST} /app/bbsTopic/create 5.3 新增帖子
     * @apiName bbsTopic create
     * @apiGroup bbsTopic
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} siteId 站点ID
     * @apiParam {int} forumId 板块ID
     * @apiParam {String} coverUrl 图片地址（可多张，逗号隔开）
     * @apiParam {String} coverType 客户端设置并解析
     * @apiParam {String} name 帖子名字
     * @apiParam {String} content 帖子内容
     * @apiParam {String} label 帖子标签
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @PostMapping("/create")
    public Object create(@NotNull @LoginUser Integer userId, @RequestBody BbsTopic entity) {
        ComplexResult check = FluentValidator.checkAll()
                .on(entity, new NotNullValidator("帖子"))
                .on(userId, new NotNullValidator("用户"))
                .on(entity.getSiteId(), new NotNullValidator("siteId"))
                .on(entity.getForumId(), new NotNullValidator("ForumId"))
                .on(entity.getCoverUrl(), new NotNullValidator("封面"))
                .on(entity.getName(), new NotNullValidator("帖子标题"))
                .on(entity.getContent(), new NotNullValidator("帖子内容"))
                .doValidate()
                .result(toComplex());
        if (!check.isSuccess()) {
            //参数校验不通过，直接返回结果并提示缺少哪些参数
            return ResponseUtil.fail(check.getErrors());
        }

        ProUser user = userService.getById(userId);

        entity.setAddTime(LocalDateTime.now());
        entity.setCreateUserId(userId);
        entity.setCreateAvatar(user.getAvatar());
        entity.setCreateNickname(user.getNickname());
        entity.setCreateUsername(user.getUsername());
        entity.setDeleted(false);
        bbsTopicService.saveTopic(entity);
        return ResponseUtil.ok();
    }

    /**
     * @api {POST} /app/bbsTopic/update 5.4 更新帖子
     * @apiName  bbsTopic update
     * @apiGroup  bbsTopic
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 帖子id
     * @apiParam {int} siteId 站点ID
     * @apiParam {int} forumId 板块ID
     * @apiParam {String} coverUrl 图片地址（可多张，逗号隔开）
     * @apiParam {String} coverType 客户端设置并解析
     * @apiParam {String} name 帖子名字
     * @apiParam {String} content 帖子内容
     * @apiParam {String} label 帖子标签
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @PostMapping("/update")
    public Object update(@LoginUser Integer userId,@RequestBody  BbsTopic entity) {
        ComplexResult check = FluentValidator.checkAll()
                .on(entity, new NotNullValidator("帖子"))
                .on(userId, new NotNullValidator("用户"))
                .on(entity.getId(), new NotNullValidator("帖子ID"))
                .on(entity.getSiteId(), new NotNullValidator("siteId"))
                .on(entity.getForumId(), new NotNullValidator("ForumId"))
                .on(entity.getCoverUrl(), new NotNullValidator("封面"))
                .on(entity.getName(), new NotNullValidator("帖子标题"))
                .on(entity.getContent(), new NotNullValidator("帖子内容"))
                .doValidate()
                .result(toComplex());
        if (!check.isSuccess()) {
            //参数校验不通过，直接返回结果并提示缺少哪些参数
            return ResponseUtil.fail(check.getErrors());
        }

        entity.setUpdateTime(LocalDateTime.now());
        bbsTopicService.updateById(entity);
        return ResponseUtil.ok();
    }

    /**
     * @api {POST} /app/bbsTopic/delete 5.5 删除帖子
     * @apiName bbsTopic delete
     * @apiGroup bbsTopic
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} id 帖子id
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @PostMapping("/delete")
    public Object delete(@LoginUser Integer userId,@RequestBody BbsTopic entity) {
        Integer id = entity.getId();
        if (id == null) {
            return ResponseUtil.fail("ID不能为空");
        }

        if (userId == null) {
            return ResponseUtil.fail("用户id");
        }

        if(entity.getCreateUserId().equals(userId)){
            return ResponseUtil.fail("不是您的帖子");
        }

        bbsTopicService.removeById(id);
        return ResponseUtil.ok();
    }


    /**
     * @api {GET} /app/bbsTopic/hotAndNew 5.6 站点首页获取全站最新/最热帖子/精华帖子/最新回复
     * @apiName bbsTopic hotAndNew
     * @apiGroup bbsTopic
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} type 1：最新发布   2：最热  3： 精华  4：最新回复
     * @apiParam {int} [siteId] 站点id 不传则查询所有站点
     * @apiParam {int} [page] 页码
     * @apiParam {int} [size] 每页数量
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/hotAndNew")
    public Object hotAndNew(@NotNull Integer type,Integer siteId,@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer size) {

        Page<BbsTopic> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        IPage<BbsTopic> pList;
        if(type == 1){
            pList = bbsTopicService.page(pageVo,
                    new QueryWrapper<BbsTopic>()
                            //.select("id","site_id","forum_id","name","add_time")
                            .eq("deleted",0)
                            .eq(siteId != null,"site_id",siteId)
                            .orderByDesc("add_time"));
        }else if (type == 2){
            pList = bbsTopicService.page(pageVo,
                    new QueryWrapper<BbsTopic>()
                           /* .select("id","site_id","forum_id","name","description","cover_url",
                                    "cover_type","label","keywords","read_num","like_num",
                                    "favor_num","hot_tag","create_user_id","create_username",
                                    "create_nickname","create_avatar")*/
                            //.select("id","site_id","forum_id","name","add_time")
                            .eq("deleted",0)
                            .eq(siteId != null,"site_id",siteId)
                            .orderByDesc("read_num"));
        }else if (type == 3){
            pList = bbsTopicService.page(pageVo,
                    new QueryWrapper<BbsTopic>()
                            /* .select("id","site_id","forum_id","name","description","cover_url",
                                     "cover_type","label","keywords","read_num","like_num",
                                     "favor_num","hot_tag","create_user_id","create_username",
                                     "create_nickname","create_avatar")*/
                            //.select("id","site_id","forum_id","name","add_time")
                            .eq("deleted",0)
                            .eq(siteId != null,"site_id",siteId)
                            .orderByDesc("like_num"));
        }else if (type == 4){
            pList = bbsTopicService.page(pageVo,
                    new QueryWrapper<BbsTopic>()
                            /* .select("id","site_id","forum_id","name","description","cover_url",
                                     "cover_type","label","keywords","read_num","like_num",
                                     "favor_num","hot_tag","create_user_id","create_username",
                                     "create_nickname","create_avatar")*/
                            //.select("id","site_id","forum_id","name","add_time")
                            .eq("deleted",0)
                            .eq(siteId != null,"site_id",siteId)
                            .orderByDesc("comment_num"));
        }else {
            return ResponseUtil.fail("类型不存在");
        }


        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }


    /**
     * @api {GET} /app/bbsTopic/count 5.7 获取统计数据
     * @apiName bbsTopic count
     * @apiGroup bbsTopic
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} [siteId] 站点id 不传则查询所有站点
     * @apiParam {int} [page] 页码
     * @apiParam {int} [size] 每页数量
     *
     * @apiSuccess {int} errno 结果码 0:正常返回,-1服务异常
     * @apiSuccess {String} errmsg 前端提示消息
     * @apiSuccess {Object} data 结果集
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/count")
    public Object count(@NotNull Integer siteId,@RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer size) {

        //今日发帖数
        int todayTopicNum = 26213;
        //今日回复数
        int todayCommentNum = 123234;
        //昨日发帖数
        int yesterdayTopicNum = 57435;
        //昨日回复数
        int yesterdayCommentNum = 234536;
        //建站时间
        String buildSiteTime = "2019-12-30";
        //总会员数量
        int totalUserNum = 234536;
        //总帖子数量
        int totalTopicNum = 2511244;
        //今日浏览量
        int todayReadNum = 30239;

        Map<String, Object> data = new HashMap<>();
        data.put("todayTopicNum", todayTopicNum);
        data.put("todayCommentNum", todayCommentNum);
        data.put("yesterdayTopicNum", yesterdayTopicNum);
        data.put("yesterdayCommentNum", yesterdayCommentNum);
        data.put("buildSiteTime", buildSiteTime);
        data.put("totalUserNum", totalUserNum);
        data.put("totalTopicNum", totalTopicNum);
        data.put("todayReadNum", todayReadNum);
        return ResponseUtil.ok(data);
    }


}

